import { ApiResponse, Article, Channel } from '@/types/data'
import { HomeAction, RootThunkAction } from '@/types/store'
import request from '@/utils/request'
import {
  getLocalChannels,
  getToken,
  hasToken,
  setLocalChannels,
} from '@/utils/storage'

//获取用户频道
export const getUserChannel = (): RootThunkAction => {
  return async (dispatch) => {
    //如果用户是登录 实时获取登录获取的频道数据
    const token = getToken().token
    if (token) {
      const res = await request.get<ApiResponse<{ channels: Channel[] }>>(
        '/user/channels'
      )
      dispatch({
        type: 'home/getUserChannels',
        payload: res.data.data.channels,
      })
    } else {
      //游客身份，尝试从本地获取频道数据
      const localChannels = getLocalChannels()
      if (localChannels) {
        //如果本地拿到了 直接用 不需要发请求
        dispatch({
          type: 'home/getUserChannels',
          payload: localChannels,
        })
      } else {
        //2.如果本地没拿到，首次访问，发请求拿默认的频道列表，且存本地
        const res = await request.get<ApiResponse<{ channels: Channel[] }>>(
          '/user/channels'
        )
        dispatch({
          type: 'home/getUserChannels',
          payload: res.data.data.channels,
        })
        setLocalChannels(res.data.data.channels)
      }
    }
  }
}

//获取所有频道
export const getAllChannels = (): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<ApiResponse<{ channels: Channel[] }>>(
      '/channels'
    )
    dispatch({
      type: 'home/getAllChannels',
      payload: res.data.data.channels,
    })
  }
}

//切换编辑状态
export const changeActive = (active: number): HomeAction => {
  return {
    type: 'home/changeActive',
    payload: active,
  }
}

//删除用户频道
export const delChannel = (id: number): RootThunkAction => {
  return async (dispatch, getState) => {
    const { userChannels } = getState().home
    if (hasToken()) {
      // 用户登录了，发送请求进行删除
      const res = await request.delete('/user/channels', {
        data: {
          channels: [id],
        },
      })
      console.log(res)
    } else {
      // 如果没有登录，本地删除一条数据
      userChannels.filter((item) => item.id !== id)
    }
    //更新渲染
    dispatch(getUserChannel())
  }
}

//添加频道
export const addChannel = (channel: Channel): RootThunkAction => {
  return async (dispatch, getState) => {
    const { userChannels } = getState().home
    if (hasToken()) {
      // 如果登录了，发送请求获取频道信息
      await request.patch('/user/channels', {
        channels: [channel],
      })
    } else {
      // 如果没有登录，将频道数据保存到本地
      // 将channels数据保存本地
      setLocalChannels([...userChannels, channel])
    }
    //更新渲染
    dispatch(getUserChannel())
  }
}

/**
 * 获取文章列表
 * @param channel_id 获取文章列表
 * @param timestamp 时间戳
 * @returns
 */
export const getArticleList = (
  channel_id: number,
  timestamp: string
): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<
      ApiResponse<{ pre_timestamp: string; results: Article[] }>
    >('/articles', {
      params: {
        channel_id,
        timestamp,
      },
    })
    // console.log(res)
    const { pre_timestamp, results } = res.data.data
    dispatch({
      type: 'home/saveChannelsArticle',
      payload: {
        channel_id,
        timestamp: pre_timestamp,
        articles: results,
      },
    })
  }
}

//
export const getArticleListRefresh = (
  channel_id: number,
  timestamp: string
): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get<
      ApiResponse<{ pre_timestamp: string; results: Article[] }>
    >('/articles', {
      params: {
        channel_id,
        timestamp,
      },
    })
    console.log(res)
    const { pre_timestamp, results } = res.data.data
    dispatch({
      type: 'home/refreshChannelsArticle',
      payload: {
        channel_id,
        timestamp: pre_timestamp,
        articles: results,
      },
    })
  }
}
